package com.clinicaltrials.utils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import java.net.URLEncoder;
import lombok.extern.slf4j.Slf4j;
/**
 * <p>Title: 客户端校验</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 广州市概点信息科技有限公司</p>
 *
 * @author laiwenjin
 * @version 1.0
 * @email 960799328@qq.com
 * @date 2020-04-29 17:43
 */
@Slf4j
public class AliPayUtil {
    public static AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.appWapid, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
    
    
    
    /*** 转码*/
    public static String getByte(String param) {
        try {
            return new String(param.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

    }

    /*** 校验签名*/
    public static boolean rsaCheckV1(HttpServletRequest request) {
        // https://docs.open.alipay.com/54/106370
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            return signVerified;
        } catch (AlipayApiException e) {
            log.debug("verify sigin error, exception is:{}", e);
            return false;
        }
    }
    
    /**
     * 拼接键值对
     *
     * @param key
     * @param value
     * @param isEncode
     * @return
     */
    private static String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        try {
			sb.append(URLEncoder.encode(value, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        
        return sb.toString();
    }
    
    /**
     * 获取签名
     * @sign
     * @param @param content
     * @param @return
     * @return String
     * @author lwj  
     * @email  1476533237@qq.com  
     * @date 2020年5月22日  
     * @version 1.0 
     * @update lwj
     * @updateDate 2020年5月22日
     */
    public static String getSign(String orderId,String money) {
    	//获取map的订单信息
    	Map<String, String> data =createContent(orderId,money);
    	//获取原始待签名内容
    	String initContent=AlipaySignature.getSignContent(data);
    	System.out.println("initContent:"+initContent);
    	//获取加密后的待签名内容，只把value加密，再将key=value拼接起来
    	String encodecontent=encodeContent(data);
    	//签名过程，首先生成privateKey，再Signature进行签名初始化initSign，最后返回加密签名
    	try {
			String sign=AlipaySignature.rsaSign(initContent, AlipayConfig.merchant_private_key, AlipayConfig.charset,AlipayConfig.sign_type);
			//秘钥加密
			String encodeSing=URLEncoder.encode(sign, "UTF-8");
			System.out.println("encodeSing:"+encodeSing);
			String orderInfo=encodecontent+"sign="+encodeSing;
			
			
			return orderInfo;
    	} catch (Exception e) {
			e.printStackTrace();
			log.error("sigin error,操作异常:{}",e);
			return null;
		}
    }
    
    /**
     * 创建加密后的订单信息
     * @createContent
     * @param @param orderId
     * @param @param money
     * @param @return
     * @return String
     * @author lwj  
     * @email  1476533237@qq.com  
     * @date 2020年5月22日  
     * @version 1.0 
     * @update lwj
     * @updateDate 2020年5月22日
     */
    public static String encodeContent(Map<String, String> data){
    	StringBuilder sb = new StringBuilder();
    	
    	List<String> keys = new ArrayList<String>(data.keySet());
    	Collections.sort(keys);
    	for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = data.get(key);
            sb.append(buildKeyValue(key, value, true));
            sb.append("&");
        }
    	System.out.println("encodeContent:"+sb.toString());
    	return sb.toString();
    }
    /**
     * 创建app待签约内容
     * @createContent
     * @param @param orderId
     * @param @param money
     * @param @return
     * @return String
     * @author lwj  
     * @email  1476533237@qq.com  
     * @date 2020年5月22日  
     * @version 1.0 
     * @update lwj
     * @updateDate 2020年5月22日
     */
    public static Map<String, String> createContent(String orderId,String money){
    	Map<String, String> data =new HashMap<>();
    	data.put("app_id", AlipayConfig.appId);
    	data.put("method", "alipay.trade.app.pay");
    	data.put("charset", AlipayConfig.charset);
    	data.put("sign_type", AlipayConfig.sign_type);
    	data.put("timestamp",DateUtils.getCurrentDateTime());
    	data.put("version", "1.0");
    	data.put("notify_url", "https://api.xx.com/receive_notify.htm");
    	data.put("biz_content", "{\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\""+money+"\",\"subject\":\""+AlipayConfig.subject+"\",\"out_trade_no\":\""+orderId+"\"}");
    	return data;
    }
   
    
}

